package com.itheima.com.controller;



import com.itheima.com.controller.result.ResUlt;
import com.itheima.com.entity.AppVersion;
import com.itheima.com.entity.DevUser;
import com.itheima.com.service.AppVersionService;
import com.itheima.com.uitls.SessionUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/version")
public class AppVersionController {
    @Resource
    AppVersionService appVersionService;
    @RequestMapping("/getVersion/{id}")
    public ResUlt getVersion(@PathVariable Long id){
        return new ResUlt(true,appVersionService.getAppInfo(id),null);
    }
        @RequestMapping("/addApk")
    public ResUlt addApk(AppVersion appVersion, MultipartFile file, HttpServletRequest request){
        String token = request.getHeader("token");
        DevUser devUser  = (DevUser) SessionUtils.get(token);
        if(file.isEmpty()){
            String realPath = request.getServletContext().getRealPath("/apk");
            File file1 = new File(realPath);
            if (file1.exists()){
                file1.mkdirs();
            }
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            if (substring.equalsIgnoreCase(".apk")) {
                if (file.getSize()<5000*1024*1024) {
                    String s = UUID.randomUUID().toString().replace("-", "") + substring;
                    appVersion.setDownloadlink(s);
                    file1 = new File(realPath + "\\" + s);
                    try {
                        file.transferTo(file1);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    return new ResUlt(false, null, "图片大小不能小于500k");
                }
            }else {
                return new ResUlt(false, null, "图片格式不正确");
            }
        }else if (devUser.getId()==null){
            return new ResUlt(false, null, "请选择图片");
        }
        return new ResUlt(appVersionService.addApk(appVersion,devUser.getId()), null, null);
    }
}
